package com.moyuxi.sound_of_the_forest

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.RequiresApi
import com.moyuxi.sound_of_the_forest.service.AudioService
import com.moyuxi.sound_of_the_forest.service.AudioService.AudioServiceBinder
import com.moyuxi.sound_of_the_forest.ui.route.RouteCompose
import com.moyuxi.sound_of_the_forest.viewModel.MainViewModel


class MainActivity : ComponentActivity() {

    private val mainVM: MainViewModel = MainViewModel(this)
    private var binder: AudioServiceBinder? = null

    private val audioSC: AudioServiceConnection = AudioServiceConnection()

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val intent = Intent(this, AudioService::class.java)
//        startService(intent)
        bindService(intent, audioSC, BIND_AUTO_CREATE)
        mainVM.loadLocalMusicByDatabase(this)
        setContent {
            RouteCompose(mainVM, binder)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(audioSC)
        mainVM.stopMusic()
        Log.i("TAG", "onDestroy: into")
    }


    inner class AudioServiceConnection : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            binder = service as AudioServiceBinder
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            binder = null
        }

    }


}

